const express = require('express');
const router = express.Router();
const {Article} = require('../../models');
const {Op} = require('sequelize');
const {NotFoundError, success, failure} = require('../../Utils/response');

/* GET 查询所有文章列表数据 */
router.get('/', async function (req, res,) {
    try {
        // 获取文章搜索条件
        const query = req.query;
        // 当前是第几页 默认第一页
        const currentPage = Math.abs(Number(query.currentPage)) || 1;
        // 分页的大小，默认10条一页
        const pageSize = Math.abs(Number(query.pageSize)) || 10;
        const condition = {
            order: [["id", "DESC"]],
            limit: pageSize,
            offset: (currentPage - 1) * pageSize,
        }
        if (query.title) {
            condition.where = {
                title: {
                    [Op.like]: `%${query.title}%`,
                }
            };
        }
        // 查询文章
        const {count, rows} = await Article.findAndCountAll(condition);
        success(res, '查询文章成功。', {
            articles: rows,
            pagination: {
                total: count,
                currentPage: currentPage,
                pageSize: pageSize,
            }
        })
    } catch (error) {
        failure(res, error);
    }
});

// 根据id查询单个文章
router.get('/:id', async function (req, res,) {
    try {
        const article = await getArticle(req);
        success(res, '查询文章成功。', {article})
    } catch (error) {
        failure(res, error);
    }
});

/* POST  创建文章数据 */
router.post('/', async function (req, res,) {
    try {
        const body = filterBody(req.body)
        const article = await Article.create(body);
        success(res, '创建文章成功。', {article}, 201)
    } catch (error) {
        failure(res, error);
    }
});

// 根据id删除单个文章
router.delete('/:id', async function (req, res,) {
    try {
        const article = await getArticle(req);
        await article.destroy();
        success(res, '删除文章成功。', {article},)
    } catch (error) {
        failure(res, error);
    }
})


// 根据id--更新单个文章
router.put('/:id', async function (req, res,) {
    try {
        const article = await getArticle(req);
        const body = filterBody(req.body)
        await article.update(body)
        success(res, '更新文章成功。', {article},)
    } catch (error) {
        failure(res, error);
    }
});

// 公共方法：查询当前文章
async function getArticle(req) {
    // 获取文章 ID
    const {id} = req.params;
    // 查询文章
    const article = await Article.findByPk(id);
    if (!article) {
        throw new NotFoundError(`ID:${id} 的文章没有找到`)
    }
    return article
}

// 公共方法：白名单过滤  ===永远不要相信用户所填写的数据
function filterBody(req) {
    return {
        title: req.title,
        content: req.content,
    }

}

module.exports = router;
